package com.leyou.auth.service.impl;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.service.UserAuthService;
import com.leyou.common.constants.RedisConstants;
import com.leyou.common.entity.Payload;
import com.leyou.common.entity.UserInfo;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.common.utils.JwtUtils;
import com.leyou.dto.UserDTO;
import com.leyou.user.client.UserClient;
import feign.FeignException;
import io.jsonwebtoken.JwtException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.TokenConstants.COOKIE_NAME;
import static com.leyou.common.constants.TokenConstants.DOMAIN;

/**
 * <h3>leyou-project</h3>
 * <p></p>
 *
 * @author : hhw
 * @date : 2020-06-06 16:25
 **/
@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private UserClient userClient;

@Autowired
private JwtProperties properties;
@Autowired
private StringRedisTemplate redisTemplate;

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) throw  new LyException(400, "用户名或密码不能为空");
        UserDTO userDTO;
        try {
            userDTO = userClient.queryUserByUsernameAndPassword(username, password);
        } catch (FeignException e) {
            throw new LyException(e.status(),e.contentUTF8(), e);
        }
        if (userDTO == null) {
            throw new LyException(400, "用户名或密码错误");
        }
        String jti = JwtUtils.createJTI();
        //生成token
        String token = JwtUtils.generateTokenWithJTI(new UserInfo(userDTO.getId(), username, null), jti, properties.getPrivateKey());

        redisTemplate.opsForValue().set(RedisConstants.JTI_KEY_PREFIX + userDTO.getId(), jti, RedisConstants.TOKEN_EXPIRE_MINUTES, TimeUnit.MINUTES);
       /* //存入response携带cookie回去
        Cookie cookie = new Cookie(COOKIE_NAME, token);

        //设置域名
        cookie.setDomain(DOMAIN);
        //设置最大存货时间,-1表示随浏览器关闭销毁
        cookie.setMaxAge(-1);
        //设置作用路径
        cookie.setPath("/");
        //设置不能用脚本更改cookie
        cookie.setHttpOnly(true);
        response.addCookie(cookie);*/
       CookieUtils.builder(response)
               .domain(DOMAIN)
               .maxAge(-1)
               .path("/")
               .httpOnly(true)
               .build(COOKIE_NAME, token);
    }

    @Override
    public String verify(HttpServletRequest request) {
        //1.获取cookie
        String token = CookieUtils.getCookieValue(request, COOKIE_NAME);
        if (StringUtils.isEmpty(token)) throw new LyException(401, "用户未登录或者超时");
        //2.验证cookie的正确性
        Payload<UserInfo> payload;
        try {
            payload = JwtUtils.getInfoFromToken(token, properties.getPublicKey(), UserInfo.class);
        } catch (JwtException e) {
            throw new LyException(401, "用户未登录或者不存在");
        }
        //3.获取cookie中的username
        UserInfo userInfo = payload.getUserInfo();
        if (userInfo == null) {
            throw new LyException(401, "用户未登录或者不存在");
        }
        String jti = redisTemplate.opsForValue().get(RedisConstants.JTI_KEY_PREFIX + userInfo.getId());
        if (!StringUtils.equals(jti, payload.getId())) {
            throw new LyException(401, "登录失效");
        }
        return userInfo.getUsername();
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            //将redis中token删除
            String token = CookieUtils.getCookieValue(request, COOKIE_NAME);
            if (StringUtils.isEmpty(token)) {
                throw new LyException(400, "未知错误,未登录不该点到这个按钮");
            }
            Payload<UserInfo> payload;
            try {
                payload = JwtUtils.getInfoFromToken(token, properties.getPublicKey(), UserInfo.class);
            } catch (JwtException e) {
                throw new LyException(400, "不存在token?");
            }
            //3.获取cookie中的username
            UserInfo userInfo = payload.getUserInfo();
            if (userInfo == null) {
                throw new LyException(400, "未知错误,未登录不该点到这个按钮");
            }
            redisTemplate.delete(RedisConstants.JTI_KEY_PREFIX + userInfo.getId());
            //将cookie时间设置为0
            CookieUtils.deleteCookie(COOKIE_NAME, DOMAIN, response);
        } catch (LyException e) {
            throw new LyException(400, "未知错误,未登录不该点到这个按钮");
        } catch (Exception e) {
            throw new LyException(500, "退出登录失败");
        }

    }
}
